package org.dromara.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.knowledge.domain.KnowledgeJob;
import org.dromara.knowledge.domain.bo.KnowledgeJobBo;
import org.dromara.knowledge.domain.vo.KnowledgeJobVo;
import org.dromara.knowledge.mapper.KnowledgeJobMapper;
import org.dromara.knowledge.service.KnowledgeJobService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 知识库任务Service业务层处理
 *
 * @author ruoyi
 */
@RequiredArgsConstructor
@Service
public class KnowledgeJobServiceImpl extends ServiceImpl<KnowledgeJobMapper, KnowledgeJob> implements KnowledgeJobService {

    private final KnowledgeJobMapper baseMapper;

    /**
     * 查询知识库任务
     */
    @Override
    public KnowledgeJobVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询知识库任务列表
     */
    @Override
    public TableDataInfo<KnowledgeJobVo> queryPageList(KnowledgeJobBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<KnowledgeJob> lqw = buildQueryWrapper(bo);
        Page<KnowledgeJobVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询知识库任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryList(KnowledgeJobBo bo) {
        LambdaQueryWrapper<KnowledgeJob> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<KnowledgeJob> buildQueryWrapper(KnowledgeJobBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getJobId()), KnowledgeJob::getJobId, bo.getJobId());
        lqw.eq(StringUtils.isNotBlank(bo.getJobType()), KnowledgeJob::getJobType, bo.getJobType());
        lqw.eq(StringUtils.isNotBlank(bo.getJobSubType()), KnowledgeJob::getJobSubType, bo.getJobSubType());
        lqw.eq(StringUtils.isNotBlank(bo.getKnowledgeId()), KnowledgeJob::getKnowledgeId, bo.getKnowledgeId());
        lqw.eq(StringUtils.isNotBlank(bo.getDocId()), KnowledgeJob::getDocId, bo.getDocId());
        lqw.eq(bo.getUserId() != null, KnowledgeJob::getUserId, bo.getUserId());
        lqw.eq(bo.getStatus() != null, KnowledgeJob::getStatus, bo.getStatus());
        lqw.eq(bo.getPriority() != null, KnowledgeJob::getPriority, bo.getPriority());
        lqw.between(params.get("beginStartTime") != null && params.get("endStartTime") != null,
                KnowledgeJob::getStartTime, params.get("beginStartTime"), params.get("endStartTime"));
        lqw.between(params.get("beginEndTime") != null && params.get("endEndTime") != null,
                KnowledgeJob::getEndTime, params.get("beginEndTime"), params.get("endEndTime"));
        return lqw;
    }

    /**
     * 新增知识库任务
     */
    @Override
    public Boolean insertByBo(KnowledgeJobBo bo) {
        KnowledgeJob add = MapstructUtils.convert(bo, KnowledgeJob.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改知识库任务
     */
    @Override
    public Boolean updateByBo(KnowledgeJobBo bo) {
        KnowledgeJob update = MapstructUtils.convert(bo, KnowledgeJob.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(KnowledgeJob entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除知识库任务
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据任务ID查询知识库任务
     */
    @Override
    public KnowledgeJobVo queryByJobId(String jobId) {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getJobId, jobId);
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 根据知识库ID查询知识库任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryByKnowledgeId(String knowledgeId) {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getKnowledgeId, knowledgeId);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据文档ID查询知识库任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryByDocId(String docId) {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getDocId, docId);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据用户ID查询知识库任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryByUserId(Long userId) {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getUserId, userId);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据任务类型查询知识库任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryByJobType(String jobType) {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getJobType, jobType);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据任务状态查询知识库任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryByStatus(Integer status) {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getStatus, status);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询正在运行的任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryRunningJobs() {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getStatus, 1); // 假设1表示运行中
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询待处理的任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryPendingJobs() {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getStatus, 0); // 假设0表示待处理
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询失败的任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryFailedJobs() {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getStatus, 3); // 假设3表示失败
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 更新任务进度
     */
    @Override
    public Boolean updateProgress(Long id, Integer progress) {
        KnowledgeJob update = new KnowledgeJob();
        update.setId(id);
        update.setProgress(progress);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 更新任务状态
     */
    @Override
    public Boolean updateStatus(Long id, Integer status) {
        KnowledgeJob update = new KnowledgeJob();
        update.setId(id);
        update.setStatus(status);
        if (status == 2) { // 假设2表示完成
            update.setEndTime(new Date());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 增加重试次数
     */
    @Override
    public Boolean incrementRetryCount(Long id) {
        KnowledgeJob job = baseMapper.selectById(id);
        if (job != null) {
            job.setRetryCount(job.getRetryCount() + 1);
            return baseMapper.updateById(job) > 0;
        }
        return false;
    }

    /**
     * 更新任务项目计数
     */
    @Override
    public Boolean updateItemCounts(Long id, Integer totalItems, Integer processedItems, Integer successItems, Integer failedItems) {
        KnowledgeJob update = new KnowledgeJob();
        update.setId(id);
        update.setTotalItems(totalItems);
        update.setProcessedItems(processedItems);
        update.setSuccessItems(successItems);
        update.setFailedItems(failedItems);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 根据优先级查询任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryByPriority(Integer priority) {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getPriority, priority);
        lqw.orderByDesc(KnowledgeJob::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询超时的任务列表
     */
    @Override
    public List<KnowledgeJobVo> queryTimeoutJobs() {
        LambdaQueryWrapper<KnowledgeJob> lqw = Wrappers.lambdaQuery();
        lqw.eq(KnowledgeJob::getStatus, 1) // 运行中的任务
                .isNotNull(KnowledgeJob::getTimeout)
                .isNotNull(KnowledgeJob::getStartTime)
                .apply("TIMESTAMPDIFF(SECOND, start_time, NOW()) > timeout");
        return baseMapper.selectVoList(lqw);
    }

}